package com.stx.crazyblog.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.sql.PreparedStatement;



import com.stx.crazyblog.entity.User;
import com.stx.crazyblog.util.JdbcUtil;

public class UserDao {
	public List<User> queryUser(User userParams)throws Exception{
		
		Connection connection = JdbcUtil.getConnection();
		
		Statement	stmt = connection.createStatement();
		
		ResultSet	rs = stmt.executeQuery("select * from tbl_user");
		
		List<User>	userList = new ArrayList<User>();
		
		while(rs.next()){
			User user = new User();
			
			user.setUid(rs.getString("1"));
			user.setUname(rs.getString("us_uname"));
			user.setPassword(rs.getString("us_password"));
			user.setBlogname(rs.getString("us_blogname"));
			
			userList.add(user);
		}
		JdbcUtil.release();
		
		return userList;
	}
	
	public  int insertUser(User user)throws Exception{
		
		
		Connection connection = JdbcUtil.getConnection();
		
		PreparedStatement ps = connection.prepareStatement(
				"insert into tbl_user(us_uid,us_uname,us_password,us_blogname) values (us_uid.nextval,?,?,?)");

		ps.setString(1, user.getUname());
		ps.setString(2, user.getPassword());
		ps.setString(3, user.getBlogname());
		
		int count =ps.executeUpdate();
		
		JdbcUtil.release();
		
		return count;
	
	}
	public User getUserByUnameAndPassword(String Uname,String Password) throws Exception{
		// 获取connection对象
		Connection connection = JdbcUtil.getConnection();
		
		// 通过connection对象获得"预编译语句"对象
		PreparedStatement ps = connection.prepareStatement("select * from tbl_user where us_uname = ? and us_password = ?");
//		测试System.out.println("121");
		
		// 设置"预编译语句"对象中的参数(从1开始计数)
		ps.setString(1, Uname);
		ps.setString(2, Password);
		
		// 执行查询获得结果集对象
		ResultSet rs = ps.executeQuery();

		// 声明用户对象
		User user = null;
		
		// 判断结果集中是否有记录
		while (rs.next()) {
			// 创建用户对象
			user = new User();

			// 将用户表记录的每一个字段的值 赋值给 "用户对象"对应的属性.
			// 即 用户对象.用户id <= 该条用户记录的uid
			user.setUid(rs.getString("us_uid"));
			user.setUname(rs.getString("us_uname"));
			user.setPassword(rs.getString("us_password"));
		}
		
		// 如果登录名密码匹配即返回一个用户对象，否则返回null
		return user;
	}



}
